﻿using System;
using WiMo.Games.Audio;
using System.IO;
using System.Windows.Controls;
using System.Windows;

namespace WiMo.Games.StandardAudio
{
    public class GameAudio : IGameAudio
    {
        public object AudioInformation {get; set;}
        private Stream _audioStream;
        private Canvas _container;

        public GameAudio(Stream stream, IGameEngine engine)
        {

            _audioStream = stream;
            var ele = new MediaElement();

            _container = engine as Canvas;
            if(_container == null)
                throw new NullReferenceException("GameEngine must inherit from UIElement");

            AudioInformation = ele;

            _container.Children.Add(MediaElement);

            Volume = 1.0f;
        }

        public void Load(IContentManager contentManager, string name)
        {
            
        }

        private MediaElement MediaElement
        {
            get
            {
                return AudioInformation as MediaElement;
            }
        }

        public void Play()
        {
            if (MediaElement.CurrentState == System.Windows.Media.MediaElementState.Stopped ||
                MediaElement.CurrentState == System.Windows.Media.MediaElementState.Paused ||
                MediaElement.CurrentState == System.Windows.Media.MediaElementState.Closed)
            {
                
                MediaElement.SetSource(_audioStream);
                MediaElement.Play();                
            }
        }

        public void Pause()
        {
            if(MediaElement.CurrentState == System.Windows.Media.MediaElementState.Playing)
                MediaElement.Pause();
        }

        public void Stop()
        {
            if (MediaElement.CurrentState == System.Windows.Media.MediaElementState.Playing)
                MediaElement.Stop();            
        }

        public float Volume
        {
            get { return (float) MediaElement.Volume; }
            set { MediaElement.Volume = value; }
        }

        public void Dispose()
        {
            var disposable = AudioInformation as IDisposable;
            if (disposable != null)
                disposable.Dispose();

            _audioStream.Dispose();
        }
    }
}
